package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

//@Component
@Slf4j
public class MyTask {
    @Autowired
    private OrderMapper orderMapper;

//    @Scheduled(cron = "0/5 * * * * ?")
//    public void testTask(){
//        log.info("任务开始了,{}", LocalDateTime.now());
//    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrder(){
        log.info("[每1分钟检查，待支付的订单状态],{}", LocalDateTime.now());
        // 构建一个时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-3);
        //select * from orders where status = 1 and order_time < time
        List<Orders> ordersList =  orderMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT,time);
        // 如果列表不为空，更新订单状态
        for(Orders orders:ordersList){
            // 更新数据库的状态，订单取消了
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("支付超时，自动取消");
            orders.setCancelTime(LocalDateTime.now());
            log.info("[取消支付超时订单],{},{}",orders.getId(),orders.getOrderTime());
            orderMapper.update(orders);
        }
    }

    //@Scheduled(cron = "0 0 1 * * ?") // 凌晨1点
    @Scheduled(cron = "0 0/3 * * * ?") // 临时测试，每隔3分钟，检查
    public void processOrder(){
        log.info("[每3分钟检查，派送中的订单状态],{}", LocalDateTime.now());
        // 构建一个时间，从当前往前推5分钟
        LocalDateTime time =LocalDateTime.now().plusMinutes(-3);
        // 状态是派送中，且小于这个时间的
        List<Orders> ordersList = orderMapper.selectByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
        // 如果列表不为空，更新订单状态
        for(Orders orders:ordersList){
            // 更新数据库的状态，修改为已完成
            orders.setStatus(Orders.COMPLETED);
            log.info("[派送中订单，自动更新为已完成],{},{}",orders.getId(),orders.getOrderTime());
            orderMapper.update(orders);
        }
    }
}
